package com.shxy.rlzy.security;

import com.shxy.rlzy.common.exception.CaptchaException;
import com.shxy.rlzy.common.lang.Const;
import com.shxy.rlzy.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: rlzy
 * @description: 验证码过滤器
 * @author: tanhao
 * @create: 2021-08-18 20:34
 */
@Component
@Slf4j
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();

        if("/login".equals(uri) && request.getMethod().equals("POST")){
            try {
                // 校验验证码
                validate(request);
            }
            catch (CaptchaException e) {
                // 如果不正确，则跳转到失败处理器
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }

        // 继续处理过滤器逻辑
        filterChain.doFilter(request, response);
    }

    // 校验验证码逻辑
    private void validate(HttpServletRequest request) {
        // 获取验证码
        String code = request.getParameter("code");
        // 获取key
        String captchaKey = request.getParameter("captchaKey");

        // 如果验证码或key为空
        if(StringUtils.isBlank(code) || StringUtils.isBlank(captchaKey)) {
            throw new CaptchaException("验证码有误!");
        }

        // 如果验证码和redis中存储的值不相等
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, captchaKey))) {
            throw new CaptchaException("验证码有误!");
        }

        // 删除redis中缓存的值，确保一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY, captchaKey);
    }
}
